/****************************************************
	文件：CoroutineContext.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/2/7 21:41:28
	功能：协程 上下文
*****************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HTFW.Core
{
    public class CoroutineContext : IContext
    {
        public ContextType ContextType { get; set; }
        public ContextScope ContextScope { get; set; }
        public Action<IContext> OnInit { get; set; }
        public Action<IContext> OnDispose { get; set; }

        Dictionary<int, IRoutineHandle> mRoutineDict;

        TIDCreator mTidCreator;


        public void Init(params object[] args)
        {
            mRoutineDict = new Dictionary<int, IRoutineHandle>();

            mTidCreator = TIDService.Instance.GetTIDCreator();

            OnInit?.Invoke(this);
        }

        public void Dispose()
        {
            StopAll();

            TIDService.Instance.DestroyTIDCreator(mTidCreator);
            mTidCreator = null;

            OnDispose?.Invoke(this);
        }

        /// <summary>
        /// 开启协程
        /// </summary>
        /// <param name="routine">协程</param>
        /// <param name="autoStartNow">是否即刻自动开启协程</param>
        /// <returns></returns>
        public int Start(IEnumerator routine, bool autoStartNow = true)
        {
            int tid = mTidCreator.Spawn();
            IRoutineHandle routineHandle = CoroutineService.Instance.Start(routine, autoStartNow);
            mRoutineDict.Add(tid, routineHandle);
            return tid;
        }

        /// <summary>
        /// 关闭协程
        /// </summary>
        /// <param name="tid"></param>
        public void Stop(int tid)
        {
            if (mRoutineDict.TryGetValue(tid, out var routineHandle))
            {
                routineHandle.Stop();
                mRoutineDict.Remove(tid);
                mTidCreator.Despawn(tid);
            }
        }

        /// <summary>
        /// 停止所有协程
        /// </summary>
        public void StopAll()
        {
            foreach (var item in mRoutineDict)
            {
                item.Value.Stop();
                mTidCreator.Despawn(item.Key);
            }

            mRoutineDict.Clear();
        }
    }
}